define(window.backboneCommon.getViewDefine("strategy.list"), function ($,require,Collection,tpl) {
    var defaultsOptions={
        campaignId:""
    };
    var pagePrivate = {
        getDefaults :function () {
            return defaultsOptions
        },
        getOptions : function (options) {
            options=$.ExtCommon.isCheckEmpty(options)?{}:options;
            return $.ExtCommon.initMergeJson(this.getDefaults(),options);
        }
    };
    var backboneView= Backbone.View.extend({
        events: {
            "click #tb_strategyList .strategy-show-info":"showStrategyInfo",
            "click #tb_strategyList .tr-strategy-info .chart-btnGroup>.btn": "changeChartTabs"
        },
        initialize: function () {
            this.modelAttach={};
            this.modelAttach.spread=this.model.get("modelSpread");
            this.modelAttach.report=this.model.get("modelReport");
            this.listenTo(this.modelAttach.spread, "bind:AllList", this.bindSpread);
            this.listenTo(this.model, "bind:PageList", this.bindList);
            this.listenTo(this.model, "update:Status", this.updStatusCallback);
            this.listenTo(this.model, "update:Price", this.updPriceCallback);
            this.listenTo(this.model, "bind:Info", this.bindInfo);
            this.listenTo(this.modelAttach.report, "bind:ReportStrategy", this.bindReport);
            this.render();
        },
        render:function(){
            var templateHtml=_.template(tpl);
            this.$el.html(templateHtml());
            return this;
        },
        initMain:function(options){
            this.elementModel={
                table:$("#tb_strategyList")
            };
            this.extObject={};
            this.pageData={initPage:false,initExtObject:{}};
            this.pageData.operateStatus=this.model.get("defOperateStatus");
            this.pageData.initChartDefault=this.modelAttach.report.get("chartDefault");
            this.pageOptions=$.ExtCommon.initMergeJson(pagePrivate.getOptions(),options);
            $("#btn_addStrategy").attr("href",$.ExtCommon.getStringConnect("#campaign/{0}/strategy",[this.pageOptions.campaignId]));
            this._initInputSearch();
            this._initTimeRange();
        },
        initPage:function(param){
            var isChangeSpread=false;
            if(!$.ExtCommon.isCheckEmpty(param.spreadId)){
                var spreadId=param.spreadId.toString();
                if(this.extObject.spread){
                    isChangeSpread=spreadId!==this.extObject.spread.getValue();
                    this.extObject.spread.init(spreadId,false);
                }else{
                    isChangeSpread=true;
                    $("#search_strategySpread").data("initValue",spreadId);
                }
            }
            var currentTime=this.getTimeRangeValue();
            var isChangeTime=param.startTime!==currentTime.startTime || param.endTime!==currentTime.endTime;
            if(isChangeTime){this.extObject.timeRange.setValue(param.startTime,param.endTime)}
            this.pageOptions= $.ExtCommon.initMergeJson(this.pageOptions,param);

            if(this.pageOptions.isRefreshSpread){
                this.collection.getSpreadList(this.pageOptions.campaignId);
            }
            if(!this.pageData.initPage){
                this.pageData.initPage=true;
                this._initPageList();
            }else{
                if(isChangeSpread||isChangeTime){this.refreshList()}
            }
        },
        _initInputSearch:function () {
            var self=this;
            self.extObject.inputSearch=$("#panel_inputSearch_strategy").ExtInputSearch({
                placeholder:"策略ID,策略名称",
                searchCallback:function () {
                    self.refreshList();
                }
            })
        },

        _initTimeRange:function () {
            var self=this;
            self.extObject.timeRange=$("#search_strategyTimeRange").ExtDatePicker({type:"range",
                addQuick:{"本月": [$.ExtMoment.initMoment().startOf('month'), $.ExtMoment.initMoment()]},
                maxDate:$.ExtMoment.initMoment(),
                startValue:$.ExtMoment.initFormat(),endValue:$.ExtMoment.initFormat(),
                changeCallback: function () {self.refreshList()}
            });
        },
        getTimeRangeValue:function(){
            var arrTime =this.extObject.timeRange.getValue();
            return {startTime:arrTime[0],endTime:arrTime[1]}
        },

        bindSpread:function () {
            var self=this;
            var res=this.modelAttach.spread.get("dataAllList");
            if(self.extObject.spread){
                var value=self.extObject.spread.getValue();
                value=$.ExtCommon.isCheckEmpty(value)?-1:value;
                self.extObject.spread.replaceData(res.data,value,false);
            }else{
                self.extObject.spread=$("#search_strategySpread").ExtSelect2({placeholder: "-推广计划-",allowClear: true,minimumResultsForSearch: 1,infoExt:{data:res.data,
                    initCallback:function(){self.pageData.initExtObject.spread=true},
                    changeCallback:function(){self.refreshList()}
                }});
            }
        },

        _initPageList: function () {
            var self=this;
            self.extObject.table=self.elementModel.table.ExtDataTable({
                columns: [
                    {data: "id", class: "w-60"},
                    {data: "name", class: ""},
                    {data: "statusName",class: "w-70 text-center"},
                    {data: "unitPrice", class: "w-100"},
                    {data: "pv",class: "w-85 text-right num-int"},
                    {data: "click",class: "w-85 text-right num-int"},
                    {data: "cr", class: "w-85 text-right num-float2"},
                    {data: "price", class: "w-85 text-right num-float2"},
                    {data: "cost",class: "w-110 text-right num-float2"}
                ],
                infoExt:{
                    ajaxDataPara:function(){
                        var param= {};
                        param.campaignId=self.pageOptions.campaignId;
                        var keyword = self.extObject.inputSearch.getValue();
                        if (!$.ExtCommon.isCheckEmpty(keyword)) {param.search = keyword;}
                        var spread ="";
                        if(self.pageData.initExtObject.spread){spread = $("#search_strategySpread").val()}
                        else{if(!$.ExtCommon.isCheckEmpty(self.pageOptions.spreadId)){spread = self.pageOptions.spreadId}}
                        if (!$.ExtCommon.isCheckEmpty(spread)) {param.spread = spread;}
                        var timeRange=self.getTimeRangeValue();
                        param= $.ExtCommon.initMergeJson(param,timeRange);
                        return param;
                    },
                    ajaxWholeCallback:function(param){self.collection.getPageList(param)}
                },
                createdRow: function (row, data) {
                    data.campaignId=self.pageOptions.campaignId;
                    var elementTd=$("td", row);
                    elementTd.eq(0).html($.ExtCommon.getStringConnect('<div class="strategy-show-info"><span>{0}</span><span class="icon-operate icon-rotate rotate-180"><i class="fa fa-angle-down"></i></span></div>',[data.id]));
                    elementTd.eq(1).html($.ExtCommon.getStringConnect('<a class="btn-operate longterm" href="#campaign/{0}/strategy/{1}">{2}</a>',[data.campaignId,data.id,data.name]));
                    self._bindTableStatusHtml(elementTd.eq(2),data);
                    elementTd.eq(3).html($.ExtCommon.getStringConnect(
                        '<div class="child-inline-block"><a id="btn_strategy_price_{0}" class="editable editable-click editable-init d-inline-block h-20" data-operate-type="price"  href="javascript:"><span class="num-float2">{1}</span></a><span>/{2}</span></div>',
                        [data.id,data.unitPrice,data.kpiName]
                    ));
                },
                drawCallback: function () {
                    $.ExtNumeric.initAll();
                    self.elementModel.table.find(".strategy-status-msg").tooltip();
                    self._initXEditable();
                    $.ExtAssist.urlParam.setUrl(self.elementModel.table.find("a"));
                }
            });
        },
        bindList:function(){
            var data=this.model.get("dataPageList");
            this.extObject.table.ajaxWholeRefreshData(data);
        },
        refreshList: function () {this.extObject.table.refresh()},

        _bindTableColumnByStatus: function (status) {
            status=$.ExtCommon.isCheckUndefined(status)?"":status.toString();
            var list=$.map(this.pageData.operateStatus,function (info) {
                if(info.showIds.indexOf(status)>-1){
                    return {value:info.id,text:info.name}
                }
            });
            return {status: status, list: list}
        },
        _bindTableStatusHtml:function (el,data) {
            if(data.isXEdit){
                var tempJsonStatus = this._bindTableColumnByStatus(data.status);
                el.html($.ExtCommon.getStringConnect(
                    '<a id="btn_strategy_status_{0}" class="editable editable-click editable-init"  data-operate-type="status" href="javascript:">{1}</a>',
                    [data.id,data.statusName]
                ));
                el.find(".editable").data({list: tempJsonStatus.list});
            } else if(data.isFail){
                el.html($.ExtCommon.getStringConnect(
                    '<span class="strategy-status-msg" data-toggle="tooltip" data-placement="right" data-container="body"  title="{1}">{0}</span>',
                    [data.statusName, data.errMsg]
                ));
            } else{
                el.html(data.statusName)
            }
        },
        _initXEditable: function () {
            var self=this;
            self.elementModel.table.find(".editable-click.editable-init").each(function () {
                var _this = $(this);
                _this.removeClass("editable-init");
                var _thisData = _this.data();
                var tr = $(this).parents("tr:first");
                var row =self.extObject.table.getRowInfo(tr);
                var rowData=row.data();
                var operateType = _thisData["operateType"];
                switch(operateType){
                    case "status":
                        _this.ExtXEditable({
                            source: _thisData.list,
                            type: "select",
                            params: function (params) {
                                var newParams= {};
                                newParams.id=rowData.id;
                                newParams.campaignId=self.pageOptions.campaignId;
                                newParams.status=$.trim(params.value);
                                return newParams;
                            },
                            infoExt:{
                                initControlOther: function () {
                                    _this.siblings(".editable-container").find("select").ExtSelect2({infoExt: {initValue: _thisData.list[0].value}});
                                },
                                ajaxWholeCallback:function (param) {
                                    $.ExtNotify.destroy();
                                    self.collection.updateStatus(param);
                                },
                                successCallback: function (res) {
                                    if(res.success){
                                        if(res.data.isXEdit){
                                            var tempJsonStatus = self._bindTableColumnByStatus(res.data.status);
                                            _this.text(res.data.statusName).data("list", tempJsonStatus.list);
                                            _this.ExtXEditable().refresh(tempJsonStatus.list);
                                        }else{
                                            self._bindTableStatusHtml(_this.parent(),res.data);
                                        }
                                        row.data().status = res.data.status;
                                        row.data().statusName = res.data.statusName;
                                    }
                                }
                            }
                        });
                        break;
                    case "price":
                        _this.ExtXEditable({
                            type: "text",
                            params: function (params) {
                                var newParams = {};
                                newParams.id=rowData.id;
                                newParams.campaignId=self.pageOptions.campaignId;
                                newParams.unitPrice =parseFloat($.trim(params.value).removesplit());
                                return newParams;
                            },
                            infoExt: {
                                validateExt: function (strValue) {
                                    var msg = "";
                                    if (parseFloat(strValue) <= 0) {
                                        msg = "输入值请大于0"
                                    }
                                    return msg
                                },
                                initControlOther: function () {
                                    $(".editable-container :text").ExtNumeric({"vMax": 99999999.99});
                                },
                                ajaxWholeCallback:function (param) {
                                    $.ExtNotify.destroy();
                                    self.collection.updatePrice(param);
                                },
                                successCallback: function (res, newValue) {
                                    row.data().price = newValue.removesplit();
                                }
                            }
                        });
                        break;
                }
            });
        },
        updStatusCallback:function () {
            var result=this.model.get("dataUpdStatus");
            $("#btn_strategy_status_"+result.req.id).ExtXEditable().ajaxWholeData(result.res);
        },
        updPriceCallback:function () {
            var result=this.model.get("dataUpdPrice");
            $("#btn_strategy_price_"+result.req.id).ExtXEditable().ajaxWholeData(result.res);
        },

        showStrategyInfo:function (e) {
            var self=this;
            var el=$(e.currentTarget);
            var tr=el.parents("tr:first");
            var row =this.extObject.table.getRowInfo(tr);
            var rowData=row.data();
            var trChart=tr.next();
            if(trChart.hasClass("tr-strategy-info")){
                this._animateStrategyInfo(trChart);
                var isResize=trChart.data("isResize");
                isResize=$.ExtCommon.isCheckBoolean(isResize)?isResize:false;
                if(!isResize){
                    setTimeout(function () {self._resizeChartOne(trChart)},350);
                }
            }else{
                var id=rowData.id;
                tr.after($("#template_strategy_info").render({id:id}));
                this.collection.getInfo({id:id,campaignId:this.pageOptions.campaignId});
            }
        },
        _animateStrategyInfo:function (tr) {
            var infoDiv=tr.find(".panel-strategy-info");
            infoDiv.stop().slideToggle(300);
            infoDiv.parent().toggleClass("hide-line");
            tr.prev().find(".strategy-show-info>.icon-operate").toggleClass("rotate-180");
        },
        bindInfo:function () {
            var result=this.model.get("dataInfo");
            if (result.res.success){
                var info=result.res.data;
                this._getReportData(info.id);
                var json={campaignId:this.pageOptions.campaignId,spaceId:info.spaceInfo.id, spaceName:info.spaceInfo.name, creativeId:info.creativeInfo.id, creativeName:info.creativeInfo.name, targetList:[]};
                if(info.targetData.time){
                    var tempTime=$.ExtCommon.convertWeekHourValue(info.targetData.time);
                    if (tempTime.selectedHtml.length > 0) {json.targetList.push({title:"时间",html:$.map(tempTime.selectedHtml, function (info) {return info}).join("")})}
                }

                if(info.targetData.area){json.targetList.push({title:"地域",html:'<div class="child-inline-block">'+ $.ExtCommon.getValueBySpan(info.targetData.area)+'</div>'})}

                var tempAudience=[];
                if(info.targetData.gender){tempAudience.push($.ExtCommon.getValueByParagraph("性别", "45", info.targetData.gender))}
                if(info.targetData.education){tempAudience.push($.ExtCommon.getValueByParagraph("学历", "45", info.targetData.education))}
                if(info.targetData.marriage){tempAudience.push($.ExtCommon.getValueByParagraph("婚恋", "45", info.targetData.marriage))}
                if(info.targetData.age) {tempAudience.push($.ExtCommon.getValueByParagraph("年龄", "45", info.targetData.age+"岁"))}
                if(tempAudience.length>0){json.targetList.push({title:"人口属性",html:tempAudience.join("")})}

                if(info.targetData.interest){json.targetList.push({title:"商业兴趣",html:'<div class="child-inline-block">'+ $.ExtCommon.getValueBySpan(info.targetData.interest)+'</div>'})}

                var tempDevice=[];
                if(info.targetData.os){tempDevice.push($.ExtCommon.getValueByParagraph("操作系统", "75", info.targetData.os))}
                if(info.targetData.connection){tempDevice.push($.ExtCommon.getValueByParagraph("联网方式", "75", info.targetData.connection))}
                if(info.targetData.telCom){tempDevice.push($.ExtCommon.getValueByParagraph("运营商", "60", info.targetData.telCom))}
                if(tempDevice.length>0){json.targetList.push({title:"移动设备",html:tempDevice.join("")})}

                var tempAppAction=[];
                if(info.targetData.category){tempAppAction.push($.ExtCommon.getValueByParagraph("分类", "45", info.targetData.category))}
                if(info.targetData.action){tempAppAction.push($.ExtCommon.getValueByParagraph("行为", "45", info.targetData.action))}
                if(info.targetData.fromDay){tempAppAction.push($.ExtCommon.getValueByParagraph("距今日", "55", json.fromDay+"天以内"))}
                if(tempAppAction.length>0){json.targetList.push({title:"APP行为",html:tempAppAction.join("")})}

                if(info.targetData.keyword){json.targetList.push({title:"关键字", html:'<div class="child-inline-block">'+ $.ExtCommon.getValueBySpan(info.targetData.keyword.split(","))+'</div>'})}
                if(info.targetData.crowd){json.targetList.push({title:"人群",html:'<div class="child-inline-block">'+ $.ExtCommon.getValueBySpan(info.targetData.crowd)+'</div>'})}
                var tr=$("#tr_strategy_"+info.id);
                tr.data("isResize",true).find(".strategy-info-data").html($("#template_strategy_info_data").render(json)).parent().show();
                this._animateStrategyInfo(tr);
                $.ExtAssist.urlParam.setUrl(tr.find("a"));
            }else{
                $.ExtNotify.error("该策略数据获取失败：" +result.res.msg)
            }
        },
        _getReportData:function (id) {
            var param={strategyId:id};
            param= $.ExtCommon.initMergeJson(param,this.getTimeRangeValue());
            var reportType = param.startTime === param.endTime ? "hour" : "day";
            this.collection.getReport(reportType,param);
        },
        bindReport:function () {
            var self=this;
            var result=self.modelAttach.report.get("dataReportStrategy");
            if(result.res.success){
                var type=result.req.type;
                var tr=$("#tr_strategy_"+result.req.strategyId);
                var element=tr.find(".strategy-info-chart");
                var options = {element:element, type: type,
                    chart: {infoDefault:this.pageData.initChartDefault, hoverTitle:"description",keyword: "description",
                        seriesType: "line", xAxisLen: type === "hour" ? -1 : 10, xOther: false, isDesc: type === "day"
                    }
                };
                $.ExtReport.initBind(options, result.res.data.list, function (resJson) {
                    var chartData=self._getMergeReportData(resJson);
                    tr.data("chartData",chartData);
                    self._bindChartData(chartData,element);
                });
            }else{
                $.ExtNotify.error("报告数据获取失败："+result.res.msg)
            }
        },
        _getMergeReportData:function(resJson){
            var json=$.ExtCommon.getJsonClone(resJson);
            json.infoChartTabsQueue = {count:2,list:["pv","click"]};
            json.infoChartDefault = this.pageData.initChartDefault;
            return json;
        },
        _bindChartData:function(chartData,element){
            if(chartData.original.list.length>0){
                element.height(230).parent().parent().show();
                element.prev().show().children().prop("disabled", false);
                var chartOption=$.ExtReport.getChartOption(chartData,{grid: {left: '5px', right: '10px', top: '25px', bottom: '5px'}});
                $.ExtReport.initECharts(element[0], chartOption);
            }else{
                var pEl=element.parent();
                pEl.hide();
                pEl.next().show().parent().show();
                element.prev().hide().children().prop("disabled", true)
            }
        },
        changeChartTabs:function (e) {
            $.ExtNotify.destroy();
            var el=$(e.currentTarget);
            var value=el.val();
            var tr=el.parents(".tr-strategy-info:first");
            var chartData=tr.data("chartData");
            if(!$.ExtCommon.isCheckEmpty(chartData)&& chartData.original.list.length>0){
                var arrValue=$.ExtReport.getChartTabsQueue(value,chartData);
                if(arrValue.length>0){
                    var chartBtnGroup=tr.find(".chart-btnGroup");
                    chartBtnGroup.find(".btn-default").toggleClass("btn-white btn-default");
                    $.each(arrValue,function(i,info){
                        chartBtnGroup.find("button[value='"+info+"']").toggleClass("btn-white btn-default");
                    });
                    var elChart=tr.find(".strategy-info-chart");
                    this._bindChartData(chartData,elChart);
                }else{
                    $.ExtNotify.error("必须保留一个!");
                }
            }
        },
        _resizeChartOne:function (tr) {
            var chartData=tr.data("chartData");
            var elChart=tr.find(".strategy-info-chart");
            this._bindChartData(chartData,elChart);
            tr.data("isResize",true);
        },
        resizeChartAll:function () {
            var self=this;
            $.each(self.elementModel.table.find(".tr-strategy-info"),function (i,item) {
                var tr=$(item);
                if(tr.find(".panel-strategy-info:visible").length>0){
                    self._resizeChartOne(tr);
                }else{
                    tr.data("isResize",false);
                }
            });
        }
    });
    var viewModel=function(options){
        this.collection= new Collection();
        this.model=this.collection.model;
        this.view=new backboneView({el:options.pElement,collection:this.collection,model:this.model});
        this.view.initMain(options);
    };
    viewModel.prototype={
        init:function (param) {
            this.view.initPage(param||{});
        },
        getTimeValue:function () {
            return this.view.getTimeRangeValue();
        },
        resizeChart:function () {
            this.view.resizeChartAll();
        }
    };
    return viewModel;
});